using System;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Windows;
using Prism.Commands;
using Prism.Mvvm;
using HandyControl.Controls;
using MessageBox = HandyControl.Controls.MessageBox;
using Window = System.Windows.Window;
using SanmaoTools.Models;
using System.IO;
using Microsoft.Win32;
using OfficeOpenXml;
using System.Data;
using System.Windows.Media;
using SqlSugar.Extensions;

namespace Tryit.ViewModels
{
    public class ElementEditDialogViewModel : BindableBase
    {
        private Element _element;
        public Element Element
        {
            get { return _element; }
            set { SetProperty(ref _element, value); }

        }
        private readonly System.Windows.Window _dialog;
        public DelegateCommand SelectFileCommand { get; }

        public DelegateCommand ConfirmCommand { get; }
        public DelegateCommand CancelCommand { get; }

        public ElementEditDialogViewModel(Element element, Window dialog)
        {
            _element = element;
            _dialog = dialog;
            SelectFileCommand = new DelegateCommand(ExecuteSelectFile);
            ConfirmCommand = new DelegateCommand(ExecuteConfirm, CanExecuteConfirm);
            CancelCommand = new DelegateCommand(ExecuteCancel);
        }

        private void ExecuteSelectFile()
        {
            var openFileDialog = new OpenFileDialog
            {
                Filter = "Excel文件|*.xlsx",
                Title = "选择Excel文件",
                ValidateNames = true,
                CheckFileExists = true,
                Multiselect = true
            };
            if (openFileDialog.ShowDialog() == true)
            {
                if (openFileDialog.FileNames.Length == 1)
                {
                    ProcessExcelFile(openFileDialog.FileNames[0]);
                }

            }

        }

        public void ProcessExcelFile(string filePath)
        {
            try
            {
                // 检查文件是否存在
                if (!File.Exists(filePath))
                {
                    throw new FileNotFoundException("找不到指定的文件。", filePath);
                }

                using (var package = new ExcelPackage(new FileInfo(filePath)))
                {
                    var workbook = package.Workbook;
                    if (workbook.Worksheets.Count == 0)
                    {
                        throw new Exception("Excel文件中没有工作表。");
                    }

                    var worksheet = workbook.Worksheets[0];
                    if (worksheet.Dimension == null)
                    {
                        throw new Exception("工作表是空的。");
                    }

                    var endRow = worksheet.Dimension.End.Row;
                    var endColumn = worksheet.Dimension.End.Column;

                    if (endRow < 2)
                    {
                        throw new Exception("Excel文件中数据行数不足。");
                    }

                    // 创建数据表来存储Excel数据
                    var dataTable = new System.Data.DataTable();
                    dataTable.TableName = Path.GetFileNameWithoutExtension(filePath);

                    // 添加文件名列
                    dataTable.Columns.Add("文件名", typeof(string));

                    // 添加列
                    for (int col = 1; col <= endColumn; col++)
                    {
                        var columnName = worksheet.Cells[1, col].Text.ToString();
                        if (string.IsNullOrEmpty(columnName))
                        {

                            columnName = $"Column {col}";
                        }
                        if (col == 1) columnName = "日期";
                        // 检查列名是否已存在
                        if (dataTable.Columns.Contains(columnName))
                        {
                            columnName = $"{columnName}_{col}";
                        }

                        dataTable.Columns.Add(columnName);
                    }

                    // 添加数据行
                    for (int row = 2; row <= endRow; row++)
                    {
                        var dataRow = dataTable.NewRow();
                        dataRow["文件名"] = Path.GetFileName(filePath);

                        for (int col = 1; col <= endColumn; col++)
                        {
                            dataRow[col] = worksheet.Cells[row, col].Text.ToString();
                        }
                        dataTable.Rows.Add(dataRow);
                    }
                    // 合并多个数据表
                    Element.Date = (DateTime?)dataTable.Rows[1]["日期"].ObjToDate();
                    string[] sp = dataTable.Rows[1]["??"].ToString().Split('-');
                    Element.Brand = sp[0] + "-" + sp[1]+"-"+sp[2];
                    Element.Transfernumber = sp[3];
                    Element.Al = dataTable.Rows[1]["Result"].ToString();
                    Element.Si = dataTable.Rows[1]["Result_5"].ToString();
                    Element.Fe = dataTable.Rows[1]["Result_6"].ToString();
                    Element.Cu = dataTable.Rows[1]["Result_7"].ToString();
                    Element.Mn = dataTable.Rows[1]["Result_8"].ToString();
                    Element.Mg = dataTable.Rows[1]["Result_9"].ToString();
                    Element.Cr = dataTable.Rows[1]["Result_10"].ToString();
                    Element.Ni = dataTable.Rows[1]["Result_11"].ToString();
                    Element.Zn = dataTable.Rows[1]["Result_12"].ToString();
                    Element.Ti = dataTable.Rows[1]["Result_13"].ToString();
                    Element.Be = dataTable.Rows[1]["Result_14"].ToString();
                    Element.Ca = dataTable.Rows[1]["Result_15"].ToString();
                    Element.Co = dataTable.Rows[1]["Result_16"].ToString();
                    Element.Ga = dataTable.Rows[1]["Result_17"].ToString();
                    Element.Na = dataTable.Rows[1]["Result_18"].ToString();
                    Element.P = dataTable.Rows[1]["Result_19"].ToString();
                    Element.Pb = dataTable.Rows[1]["Result_20"].ToString();
                    Element.Sb = dataTable.Rows[1]["Result_21"].ToString();
                    Element.Sn = dataTable.Rows[1]["Result_22"].ToString();
                    Element.Sr = dataTable.Rows[1]["Result_23"].ToString();
                    Element.V = dataTable.Rows[1]["Result_24"].ToString();
                    Element.Zr = dataTable.Rows[1]["Result_25"].ToString();

                    // 只需要通知Element对象变更
                    RaisePropertyChanged(nameof(Element));
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message,"错误");
            }
        }



        private bool CanExecuteConfirm()
        {
            var context = new ValidationContext(_element);
            var results = new System.Collections.Generic.List<ValidationResult>();
            return Validator.TryValidateObject(_element, context, results, true);
        }

        private void ExecuteConfirm()
        {
            if (!CanExecuteConfirm())
            {
                MessageBox.Show("请检查输入的数据是否有效", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            _dialog.DialogResult = true;
            _dialog.Close();
        }

        private void ExecuteCancel()
        {
            _dialog.DialogResult = false;
            _dialog.Close();
        }
    }
}